import React from 'react'
import { Col, Form, Input, InputNumber, Icon, Modal, Row, Radio, Button, message } from 'antd'
import { Loader } from 'components'
import LwjUpload from 'components/LwjUpload/LwjUpload'
import styles from './index.less'

const FormItem = Form.Item
const GradesModal = ({
  dispatch,
  form: {
    getFieldDecorator,
    validateFields,
    setFieldsValue,
  },
  visible,
  list,
  loading
}) => {

  const hideGradesModal = () => {
    dispatch({
      type: 'grades/toggleGradesVisible',
      gradesModalVisible: false
    })
    dispatch({
      type: 'grades/setCopyGrades',
      copyList: []
    })
  }

  const addItem = (index) => {
    list.splice(index+1,0,{});
    dispatch({
      type: 'grades/setCopyGrades',
      copyList: list
    })
  }

  const delItem = (index) => {
    if(list[index].id){
      Modal.confirm({
        title: '删除确认',
        content: '删除已保存的等级编码，对应的等级特权配置也会清除，确定要继续吗？',
        okText: '继续',
        onOk() {
          list.splice(index,1);
          dispatch({
            type: 'grades/setCopyGrades',
            copyList: list
          })
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }else{
      list.splice(index,1);
      dispatch({
        type: 'grades/setCopyGrades',
        copyList: list
      })
    }
  }

  const confirmEditModal = (e) => {
    for(let i = 0, len = list.length; i < len; i++){
      let val = list[i];
      if(!val.name || ((i != 0) && val.minScore == null) || (((i+1) != len) && val.maxScore == null)){
        message.error("积分等级未填写完整，请检查后提交");
        return;
      }
    }
    let _listSort = list.sort(compare('minScore'));
    if(!checkScore(_listSort)){
      message.error("等级积分设置有交叉，请检查后提交");
      return;
    }
    list.map(val => {
      delete val.privilegeInfoList;
      return val;
    })
    dispatch({
      type: 'grades/editGrades',
      list: list
    })
  }

  function checkScore(list){

    for(let i = 0, len = list.length; i<len; i++){

      let val = list[i];

      if(list[i + 1] && (parseInt(val.maxScore) + 1 != list[i + 1].minScore)){
        return false;
      }

    }

    return true;
  }

  function compare(property){
    return function(a,b){
      var value1 = a[property];
      var value2 = b[property];
      return value1 - value2;
    }
  }

  const xlsProps = {
    target: '/services/upload/level',
    uploadIcon: 'upload',
    accept: 'image/*',
    fileType: '',
    maxfile: 1,
    onChange (value, key) {
      list[key].iconPath = value;
      dispatch({
        type: 'grades/setCopyGrades',
        copyList: list
      })
    },
    showUploadList: true
  }

  const changeField = (value, index, field) => {
    list[index][field] = value;
    dispatch({
      type: 'grades/setCopyGrades',
      copyList: list
    })
  }

  const changeScore = (value, index, field) => {
    list[index][field] = (value ? (value.replace(/\D/g,'')-0) : null);
    dispatch({
      type: 'grades/setCopyGrades',
      copyList: list
    })
  }

  return (
    <Modal 
      visible={visible} 
      width={900} 
      title={"设置等级与积分"} 
      className={styles.memberGradeModal} 
      onCancel={hideGradesModal}
      footer={[
        <Button key="back" onClick={hideGradesModal}>关闭</Button>,
        <Button key="submit" type="primary" onClick={(e) => { confirmEditModal(e) }}>确定</Button>
      ]}>
        <Row className={styles.gradeRow}>
          <Col span={3} align="center"><em>*</em>数据类型</Col>
          <Col span={3} align="center"><em>*</em>等级名称</Col>
          <Col span={7} align="center"><em>*</em>积分范围(包含所填数值)</Col>
          <Col span={3} align="center">图标</Col>
          <Col span={6} align="center">描述</Col>
          <Col span={2} justify="start"></Col>
        </Row>
        <Form>
          {
            list.map((val, index) => (
              <Row className={styles.gradeRow} key={index}>
                {
                  val.id 
                  ? (<Col span={3} align="center" className={styles.saved}>已保存</Col>)
                  : (
                      index == 0 || ((index +1) == list.length)
                      ? <Col span={3} align="center" className={styles.base}>预设</Col>
                      : <Col span={3} align="center" className={styles.new}>新添加</Col>
                    )
                }
                <Col span={3} align="center">
                  <Input placeholder={index == 0 ? '初等级' : ((index +1) == list.length ? '末等级' : '请输入')} value={val.name} onChange={(e) => changeField(e.target.value, index, 'name')}/>
                </Col>
                <Col span={3} align="center">
                  <div className={styles.inputWidth}>
                    {
                      index == 0
                      ? '0'
                      : (<Input min={0} precision={0} step="1" value={val.minScore} onChange={(e) => changeScore(e.target.value, index, 'minScore')}/>)
                    }
                  </div>
                </Col>
                <Col span={1} align="center" className={styles.inputGap}>
                  &nbsp;&nbsp;—&nbsp;&nbsp;
                </Col>
                <Col span={3} align="center">
                  <div className={styles.inputWidth}>
                    {
                      (index+1) == list.length
                      ? '以上'
                      : (<Input min={0} precision={0} step="1" value={val.maxScore} onChange={(e) => changeScore(e.target.value, index, 'maxScore')}/>)
                    }
                  </div>
                </Col>
                <Col span={3} align="center">
                   <LwjUpload {...xlsProps} fileLists={val.iconPath || ''} index={index}/>
                </Col>
                <Col span={6} align="center">
                  <Input value={val.memo} onChange={(e) => changeField(e.target.value, index, 'memo')}/>
                </Col>
                <Col span={2} align="start">
                  {
                    (index +1) == list.length
                    ? null : <Icon type="plus-circle" theme="filled" className={styles.plus} onClick={() => addItem(index)}/>
                  }
                  {
                    index == 0 || ((index +1) == list.length)
                    ? null : <Icon type="minus-circle" theme="filled" className={styles.minus} onClick={() => delItem(index)}/>
                  }
                </Col>
              </Row>
            ))
          }
        </Form>
      <Loader spinning={loading.effects['grades/query']} />
      <Loader spinning={loading.effects['grades/editGrades']} />
    </Modal>
  )

}

export default Form.create()(GradesModal)